<template>
  <Form class="xtx-form"  ref="target" :validation-schema="mySchema" v-slot="{errors}" autocomplete="off">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}}欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>

    <div  class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field class="input"
         name="mobile"
         v-model="formData.mobile"
          :class="{err:errors.mobile}"
         type="text" placeholder="绑定的手机号" />
      </div>
        <!-- 约定显示校验错误结果 -->
         <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field class="input"
         v-model="formData.code"
         name='code'
          :class="{err:errors.code}"
        type="text" placeholder="短信验证码" />
        <span class="code" @click='send'>{{time===0 ? "发送验证码":`${time}秒后发送`}}</span>
      </div>
      <div class="error"  v-if="errors.code">{{errors.code}}</div>
    </div>

    <a @click="submit" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { useStore } from 'vuex'
import Message from '@/components/message'
import { userQQBindCode } from '@/api/user'
import { useCountdown } from '@/compositions/index'
import { Form, Field } from 'vee-validate'
import { ref, reactive } from 'vue'
import QC from 'qc'
// 校验规则
import { mobile, code } from '@/utils/validate'
import router from '@/router'
export default {
  name: 'CallbackBind',
  components: { Form, Field }, // 局部注册
  props: { unionId: { type: String, required: true } },
  setup (props) {
    // 表单引用
    const target = ref(null)
    // 1. 定义数据项：qq头像 昵称
    const nickname = ref('')
    const avatar = ref('')
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        avatar.value = res.data.figureurl_2
        nickname.value = res.data.nickname
      })
    }
    // 表单数据对象
    const formData = reactive({
      mobile: '13241051259',
      code: ''
    })
    // 校验规则
    const mySchema = {
      mobile: mobile,
      code: code
    }
    const store = useStore()
    const doQQBindLogin = async () => {
      try {
        await store.dispatch('user/userQQBindLogin', {
          unionId: props.unionId,
          mobile: formData.mobile,
          code: formData.code
        })
        await store.dispatch('cart/mergeLocalCart')
        Message({ type: 'success', text: '绑定成功' })
        router.push('/')
      } catch (error) {
        Message({ type: 'error', text: '绑定失败' })
      }
    }

    // 手动兜底校验
    const submit = () => {
      target.value.validate().then(valid => {
        if (valid) {
          doQQBindLogin()
        }
      })
    }

    const { time, start } = useCountdown()
    const send = () => {
      // 发验证码
      // 单做表单项验证-手机号是否格式正确
      if (mobile(formData.mobile) !== true) {
        return
      }
      if (time.value !== 0) {
        return
      }
      // 调用api发送验证码
      userQQBindCode(formData.mobile).then(data => {
        console.log('userQQBindCode', data)
        Message({ type: 'success', text: '验证码已发送' })
        start(60)
      }).catch(err => {
        console.log(err)
        Message({ type: 'error', text: err.response.data.message })
      })
    }

    return { time, send, nickname, avatar, formData, mySchema, submit, target }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
